# -*- coding: utf-8 -*-
"""
HaaS506 RTU 配置管理模块
简化版本 - 单文件配置管理
"""

import ujson as json
import uos

# 全局配置
_config = None
_config_file = "/haas/config.json"

# 系统状态
g_network_ready = False
g_mqtt_connected = False
g_time_synced = False
g_system_status = "starting"


def load_config():
    """加载配置文件 - 简化的3步流程"""
    global _config
    import utime

    print("[CONFIG] Starting simplified config load process")

    # 步骤1: 先判断 device_sn.txt 是否存在
    device_sn_from_file = None
    try:
        with open("/haas/device_sn.txt", "r") as f:
            device_sn_from_file = f.read().strip()
            print(
                "[CONFIG] Step 1: Found device_sn.txt: {}".format(device_sn_from_file)
            )
    except:
        print("[CONFIG] Step 1: device_sn.txt not found")
        # 如果不存在，尝试从现有配置中获取
        try:
            with open("/haas/config.json", "r") as f:
                temp_config = json.load(f)
                device_sn_from_config = temp_config.get("device", {}).get("device_sn")
                if (
                    device_sn_from_config
                    and str(device_sn_from_config) != "10000"
                    and str(device_sn_from_config) != "unknown"
                ):
                    print(
                        "[CONFIG] Step 1: Creating device_sn.txt with value from config: {}".format(
                            device_sn_from_config
                        )
                    )
                    try:
                        with open("/haas/device_sn.txt", "w") as f:
                            f.write(str(device_sn_from_config))
                        device_sn_from_file = device_sn_from_config
                        print("[CONFIG] Step 1: device_sn.txt created successfully")
                    except Exception as e:
                        print(
                            "[CONFIG] Step 1: Failed to create device_sn.txt: {}".format(
                                e
                            )
                        )
        except:
            print("[CONFIG] Step 1: No valid device_sn found in config")

    # 步骤2: 判断 /luadb/config.json 是否存在，如果存在则迁移
    try:
        luadb_files = uos.listdir("/luadb/")
        if "config.json" in luadb_files:
            print("[CONFIG] Step 2: Found /luadb/config.json, checking versions")
            
            # 合宙780芯片特性：等待文件系统稳定
            utime.sleep(1)
            
            # 读取两个文件的版本号进行比较
            need_migration = False
            luadb_version = None
            haas_version = None
            
            # 读取 /luadb/config.json 的版本
            try:
                with open("/luadb/config.json", "r") as f:
                    luadb_config = json.load(f)
                    luadb_version = luadb_config.get("system", {}).get("version", "unknown")
                print("[CONFIG] Step 2: /luadb/config.json version: {}".format(luadb_version))
            except Exception as e:
                print("[CONFIG] Step 2: Failed to read /luadb/config.json: {}".format(e))
            
            # 读取 /haas/config.json 的版本（如果存在）
            try:
                with open("/haas/config.json", "r") as f:
                    haas_config = json.load(f)
                    haas_version = haas_config.get("system", {}).get("version", "unknown")
                print("[CONFIG] Step 2: /haas/config.json version: {}".format(haas_version))
            except:
                print("[CONFIG] Step 2: No existing /haas/config.json or read failed")
                # 如果 /haas/config.json 不存在，需要迁移
                need_migration = True
            
            # 判断是否需要迁移
            if luadb_version and luadb_version != "unknown":
                if haas_version is None:
                    # /haas/config.json 不存在，需要迁移
                    need_migration = True
                    print("[CONFIG] Step 2: Need migration - no existing /haas/config.json")
                elif luadb_version != haas_version:
                    # 版本不同，需要迁移
                    need_migration = True
                    print("[CONFIG] Step 2: Need migration - version mismatch: {} != {}".format(luadb_version, haas_version))
                else:
                    print("[CONFIG] Step 2: Same version ({}), skip migration".format(luadb_version))
            
            # 执行迁移
            if need_migration:
                try:
                    # 先删除旧的 /haas/config.json
                    try:
                        uos.remove("/haas/config.json")
                        print("[CONFIG] Step 2: Removed old /haas/config.json")
                    except:
                        pass
                    
                    # 重命名文件（在只读区域实际是复制）
                    uos.rename("/luadb/config.json", "/haas/config.json")
                    print("[CONFIG] Step 2: Copied /luadb/config.json to /haas/config.json")
                    
                    # 合宙780芯片特性：等待文件系统同步
                    utime.sleep(1)
                    
                except Exception as e:
                    print("[CONFIG] Step 2: Migration failed: {}".format(e))
    except Exception as e:
        print("[CONFIG] Step 2: Cannot access /luadb/: {}".format(e))

    # 步骤3: 加载配置并更新 device_sn
    try:
        with open(_config_file, "r") as f:
            _config = json.load(f)
        print("[CONFIG] Step 3: Config loaded successfully")

        # 如果有持久化的 device_sn，更新到配置中
        if (
            device_sn_from_file
            and device_sn_from_file != "10000"
            and device_sn_from_file != "unknown"
        ):
            if "device" not in _config:
                _config["device"] = {}

            # 只有当配置中的 device_sn 不同时才更新
            config_device_sn = _config["device"].get("device_sn")
            if str(config_device_sn) != str(device_sn_from_file):
                print(
                    "[CONFIG] Step 3: Updating device_sn in config: {} -> {}".format(
                        config_device_sn, device_sn_from_file
                    )
                )
                _config["device"]["device_sn"] = device_sn_from_file

                # 保存更新后的配置
                try:
                    with open(_config_file, "w") as f:
                        f.write(json.dumps(_config))
                    print("[CONFIG] Step 3: Config saved with updated device_sn")
                except Exception as e:
                    print("[CONFIG] Step 3: Failed to save config: {}".format(e))

        print("[CONFIG] Simplified config load completed")
        print("[CONFIG] Current config: {}".format(_config))
        return True

    except Exception as e:
        print("[CONFIG] Step 3: Failed to load config: {}".format(e))
        _config = None
        return False


def get_config(key_path=None, default_value=None):
    """获取配置值"""
    # 减少调试日志输出
    # print("[CONFIG-DEBUG] get_config called with key_path: {}, default_value: {}".format(key_path, default_value))

    if _config is None:
        # print("[CONFIG-DEBUG] _config is None, loading config...")
        load_config()

    if not key_path:
        return _config

    # print("[CONFIG-DEBUG] Current _config: {}".format(_config))

    keys = key_path.split(".")
    value = _config

    try:
        for key in keys:
            # print("[CONFIG-DEBUG] Looking for key '{}' in value: {}".format(key, value))
            value = value[key]
        # print("[CONFIG-DEBUG] Found value: {}".format(value))
        return value
    except (KeyError, TypeError) as e:
        # print("[CONFIG-DEBUG] Key not found or type error: {}, returning default".format(e))
        return default_value


def set_config(key_path, value):
    """设置配置值"""
    global _config

    if _config is None:
        load_config()

    if _config is None:
        return False

    keys = key_path.split(".")
    current = _config

    try:
        for key in keys[:-1]:
            if key not in current:
                current[key] = {}
            current = current[key]

        current[keys[-1]] = value

        # 不再自动触发 device_sn 持久化，需要显式调用
        return save_config()
    except Exception as e:
        print("[CONFIG] Failed to set config: {}".format(e))
        return False


def save_config():
    """保存配置到文件（使用原子写入）"""
    global _config

    if _config is None:
        return False

    try:
        import uos

        # 1. 先写入临时文件
        temp_file = _config_file + ".tmp"
        with open(temp_file, "w") as f:
            f.write(json.dumps(_config))

        # 2. 验证临时文件
        with open(temp_file, "r") as f:
            verify_config = json.load(f)

        # 3. 验证关键字段
        if "device" not in verify_config:
            print("[CONFIG] Error: Saved config missing 'device' section")
            return False

        # 4. 删除旧文件（如果存在）
        try:
            uos.remove(_config_file)
        except:
            pass  # 文件可能不存在

        # 5. 重命名临时文件为正式文件
        uos.rename(temp_file, _config_file)

        print("[CONFIG] Config saved successfully")
        return True

    except Exception as e:
        print("[CONFIG] Failed to save config: {}".format(e))
        # 清理临时文件
        try:
            uos.remove(temp_file)
        except:
            pass
        return False


def get_device_sn():
    """获取设备序列号"""
    device_sn = get_config("device.device_sn", "unknown")

    # 如果device_sn是默认值10000，尝试从持久化文件恢复
    if device_sn == 10000 or device_sn == "10000":
        try:
            # 尝试从持久化文件读取真实的device_sn
            with open("/haas/device_sn.txt", "r") as f:
                saved_sn = f.read().strip()
            if saved_sn and saved_sn != "10000":
                print(
                    "[CONFIG] Recovered device_sn from persistent file: {}".format(
                        saved_sn
                    )
                )
                # 更新内存中的配置，但不立即保存到文件
                # 直接更新内存配置，避免触发持久化保存
                if _config is not None:
                    if "device" not in _config:
                        _config["device"] = {}
                    _config["device"]["device_sn"] = saved_sn
                return saved_sn
        except:
            pass

    return device_sn


def save_device_sn_persistent(device_sn, source="unknown"):
    """持久化保存device_sn到单独的文件（只允许特定来源）"""
    import uos

    # 只保存非默认的device_sn
    if (
        not device_sn
        or device_sn == "unknown"
        or device_sn == 10000
        or device_sn == "10000"
    ):
        print("[CONFIG] Invalid device_sn, skip saving: {}".format(device_sn))
        return False

    # 检查文件是否已存在
    try:
        with open("/haas/device_sn.txt", "r") as f:
            existing_sn = f.read().strip()

        # 如果文件已存在且不是 TTL 来源，拒绝修改
        if source != "ttl":
            print(
                "[CONFIG] WARNING: device_sn file already exists with value: {}".format(
                    existing_sn
                )
            )
            print(
                "[CONFIG] Only TTL source can modify existing device_sn, current source: {}".format(
                    source
                )
            )
            return False
        else:
            print(
                "[CONFIG] TTL source updating device_sn from {} to {}".format(
                    existing_sn, device_sn
                )
            )
    except:
        # 文件不存在，可以创建
        print("[CONFIG] Creating new device_sn file, source: {}".format(source))

    # 执行保存
    try:
        # 1. 写入临时文件
        temp_file = "/haas/device_sn.tmp"
        with open(temp_file, "w") as f:
            f.write(str(device_sn))

        # 2. 验证临时文件
        with open(temp_file, "r") as f:
            verify_sn = f.read().strip()

        if verify_sn != str(device_sn):
            print(
                "[CONFIG] Verification failed, written: {}, expected: {}".format(
                    verify_sn, device_sn
                )
            )
            uos.remove(temp_file)
            return False

        # 3. 删除旧文件（如果存在）
        try:
            uos.remove("/haas/device_sn.txt")
        except:
            pass

        # 4. 重命名临时文件为正式文件
        uos.rename(temp_file, "/haas/device_sn.txt")

        print(
            "[CONFIG] Saved device_sn to persistent file: {} (source: {})".format(
                device_sn, source
            )
        )
        return True

    except Exception as e:
        print("[CONFIG] Failed to save device_sn: {}".format(e))
        # 清理临时文件
        try:
            uos.remove(temp_file)
        except:
            pass
        return False


def get_mqtt_config():
    """获取MQTT配置"""
    device_sn = get_device_sn()
    # 如果 device_sn 是空 ，则使用默认值
    if device_sn == "unknown" or device_sn == "10000" or device_sn == "":
        device_sn = "10000"
    product_id = get_config("device.product_id", "1946094620405432320")
    mqtt_secret = get_config("device.mqtt_secret", "12345")

    return {
        "broker": get_config("mqtt.broker", "47.116.78.156"),
        "port": get_config("mqtt.port", 1883),
        "client_id": "{}${}${}".format(device_sn, product_id, mqtt_secret),
        "username": get_config("mqtt.username", "liuzong"),
        "password": get_config("mqtt.password", "liuzong888@iot"),
        "keepalive": get_config("mqtt.keepalive", 60),
        "qos": get_config("mqtt.qos", 1),
        "topics": {
            "data": "/apcc/{}/{}/properties/report".format(product_id, device_sn),
            "control": "/apcc/{}/{}/properties/write".format(product_id, device_sn),
            "status": "/apcc/{}/{}/properties/status".format(product_id, device_sn),
        },
    }


def get_intervals():
    """获取时间间隔配置"""
    # 恢复原始默认值
    default_intervals = {
        "data_collection": 10,
        "mqtt_upload": 30,
        "network_check": 60,
        "status_report": 300,
    }

    print(
        "[CONFIG-DEBUG] Getting intervals, default values: {}".format(default_intervals)
    )
    config = get_config("intervals", default_intervals)
    print("[CONFIG-DEBUG] Got intervals from config: {}".format(config))
    print("[CONFIG-DEBUG] Type of config: {}".format(type(config)))

    # 检查配置是否正确加载
    if config == default_intervals:
        print("[CONFIG-WARNING] Using default intervals, config may not be loaded!")

    return config


def init():
    """初始化配置"""
    return load_config()


# 自动加载配置 - 添加调试信息
print("[CONFIG] Module loading, attempting auto-load config...")
try:
    if load_config():
        print("[CONFIG] Auto-load successful")
    else:
        print("[CONFIG] Auto-load failed")
except Exception as e:
    print("[CONFIG] Auto-load exception: {}".format(e))
